package com.ews.onlineexchange.controller.assess;

import java.util.Calendar;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ews.onlineexchange.enumType.RecordStatus;
import com.ews.onlineexchange.model.assess.AssessRecord;
import com.ews.onlineexchange.model.assess.PeriodType;
import com.ews.onlineexchange.service.EntityQuery;

@Model
public class NeedRollbackAssessRecordList extends EntityQuery<AssessRecord> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<AssessRecord> entity ) {
		
		List<Predicate> restrictions = super.getRestrictions( cb, entity );
		
		restrictions.add( cb.equal( entity.get( "recordStatus" ), RecordStatus.Keeped ) );
		restrictions.add( cb.isFalse( entity.get( "override" ) ) );
		restrictions.add( cb.isFalse( entity.get( "rolledback" ) ) );
		
		Calendar cal = Calendar.getInstance();		
		
		Predicate yearPeriodRestriction = cb.and( 
				cb.equal( entity.join( "dict" ).get( "periodType" ), PeriodType.Year ),
				cb.lessThan( entity.get( "periodYear" ), cal.get( Calendar.YEAR ) - 1 )
		);
		
		Predicate seasonPeriodRestriction = cb.and( 
				cb.equal( entity.join( "dict" ).get( "periodType" ), PeriodType.Season ),
				cb.or( 
						cb.lessThan( entity.get( "periodYear" ), cal.get( Calendar.YEAR ) - 1 ),
						cb.lessThan( entity.get( "periodSeqNo" ), cal.get( Calendar.MONTH ) / 3 )
				)
		);
		
		Predicate monthPeriodRestriction = cb.and( 
				cb.equal( entity.join( "dict" ).get( "periodType" ), PeriodType.Month ),
				cb.or( 
						cb.lessThan( entity.get( "periodYear" ), cal.get( Calendar.YEAR ) - 1 ),
						cb.lessThan( entity.get( "periodSeqNo" ), cal.get( Calendar.MONTH ) )
				)
		);
		
		restrictions.add( cb.or( yearPeriodRestriction, seasonPeriodRestriction, monthPeriodRestriction ) );
		
		return restrictions;
		
	}
	
}
